package org.example.exception;

import java.io.*;
import java.lang.ref.Reference;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * cd base/target/classes
 * javap -c org/example/exception/ExceptionDemo.class
 */
public class ExceptionDemo {

    public static void main(String[] args) throws IOException {
        ExceptionDemo exceptionDemo=new ExceptionDemo();
        //exceptionDemo.processResources();
        exceptionDemo.processResources2();
    }

    /**
     * try-catch
     * @throws IOException
     */
    /*public void processResources() throws IOException {

        //开头使用/表示从类的根路径下开始查找
        String filePath=ExceptionDemo.class.getResource("/test/file.txt").getFile();

        FileInputStream fis = new FileInputStream(filePath);
        BufferedReader br = new BufferedReader(new InputStreamReader(fis));

        try {
            char[] buffer=new char[1024];
            int len=0;
            while ((len=br.read(buffer,0,1024))!=-1){
                System.out.println(new String(buffer,0,len));
            }
        } catch (Exception e) {
            // 异常处理...
        } finally {
            if (br != null) {
                br.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }*/

    /**
     * try-with-resources
     * 通过javap 可以看到调用了BufferedReader的close方法
     * @throws IOException
     */
    public void processResources2() throws IOException {
        //开头使用/表示从类的根路径下开始查找
        String filePath=ExceptionDemo.class.getResource("/test/file.txt").getFile();

        try(
            FileInputStream fis = new FileInputStream(filePath);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
        ){
            char[] buffer=new char[1024];
            int len=0;
            while ((len=br.read(buffer,0,1024))!=-1){
                System.out.println(new String(buffer,0,len));
            }
        }
    }

}
